﻿using LdtDataEngin.ModuleDetail.PersonnelAnalysis.PersonnelModel.Personnel;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataConversion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.PersonnelAnalysis.PersonnelModel.Personnel
{
    public class PersonelExtratSupplement
    {
        public DataContext datacontext;
        public string MatchParameterStr = "Prosecutor=2,89,164;Accused=1,90;Defender=168,169,13,99,100,101,102,103;Proxy=170,171,172,173,178,180;ProseProxy=2,89,164;AccusedProxy=1,90;Judger=t1,t2,t5,t4,t9;clerk=t6;";
        /// <summary>
        /// <summary>
        /// 要素转换表配置
        /// </summary>
        public ConverDataTabelModel ConverDataTabelModelConfig;
        /// <summary>
        /// 表对象
        /// </summary>
        public Dictionary<string, List<Dictionary<string, string>>> DicTable = new Dictionary<string, List<Dictionary<string, string>>>();

        public string xmlconfig = "";
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="config"></param>
        public void Extrat(string config)
        {
            //XmlDocument xml1 = new XmlDocument();
            //xml1.Load(@"D:\1.xml");
            //ConverDataTabelModelConfig = XmlUtility.DeserializeToObject<ConverDataTabelModel>(xml1.OuterXml);
            ConverDataTabelModelConfig = XmlUtility.DeserializeToObject<ConverDataTabelModel>(config);
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(datacontext.DataLayerAns.BcXML);
            
            SetDicTabel("", null, xmlDocument.SelectSingleNode("/*").ParentNode, datacontext);
            List<An_anjianshiti> an_AnjianshitisList = new List<An_anjianshiti>();
            foreach (var model in DicTable)
            {
                foreach (var modepaer in model.Value)
                {
                    if (modepaer.Count>0)
                    {
                        if (modepaer.ContainsKey("name") && modepaer.ContainsKey("suitdegreeid"))
                        {
                            string suitName = modepaer["name"];
                            string suitDegree = modepaer["suitdegreeid"];
                            string getsex = "";

                            if (!string.IsNullOrWhiteSpace(suitName))
                            {
                                An_anjianshiti anjianshiti = new An_anjianshiti();
                                anjianshiti.Bieming = suitDegree;
                                anjianshiti.Mingcheng = suitName;
                                anjianshiti.Xingbie = getsex;
                                an_AnjianshitisList.Add(anjianshiti);
                            }
                        }
                    }
                    
                    

                }
            }

            PersonnelFill(an_AnjianshitisList);

            PersonnelBaseClass personnelBaseClass = new PersonnelBaseClass(datacontext) { xmlconfig = xmlconfig };
            personnelBaseClass.Loade();
        }
        /// <summary>
        /// 填充人员实体内容
        /// </summary>
        /// <param name="entityResultsList"></param>
        private void PersonnelFill(List<An_anjianshiti> an_AnjianshitisList)
        {
            string caseetiyinfoid = "";
            string caseAngerid = "";
            foreach (var entity in an_AnjianshitisList)
            {
                //人员基础信息
                An_anjianshiti anjianshiti = new An_anjianshiti();


                anjianshiti.Anjianshitiid = Snowflake.Instance().GetId().ToString();
                anjianshiti.Mingcheng = entity.Mingcheng;
                if (!string.IsNullOrEmpty(entity.Xingbie))
                {
                    anjianshiti.Xingbie = DictionariesConver.DictionaryValue(entity.Xingbie, entity.Anjianshitiid);
                }

                An_anjianshitijuese juese = new An_anjianshitijuese();
                juese.Anjianshitiid = anjianshiti.Anjianshitiid;
                juese.Jueseid = Snowflake.Instance().GetId().ToString();

                juese.Juesesusongdiwei = DictionariesConver.DictionaryValue(entity.Bieming, entity.Dizhi);
                juese.Juesexuhao = PersonnelReadIndex(juese.Juesesusongdiwei);
                juese.SusongDiwei = entity.Bieming;

                juese.Juesemingcheng = GetArgumentValueByMatchWords(MatchParameterStr, juese.Juesesusongdiwei);
                if (juese.Juesesusongdiwei == "90" || juese.Juesesusongdiwei == "89"
                    || juese.Juesesusongdiwei == "1" || juese.Juesesusongdiwei == "7" ||
                    juese.Juesesusongdiwei == "13" || juese.Juesesusongdiwei == "155" ||
                    juese.Juesesusongdiwei == "156" || juese.Juesesusongdiwei == "157" ||
                    juese.Juesesusongdiwei == "19" || juese.Juesesusongdiwei == "29"
                    )
                {
                    caseetiyinfoid = juese.Juesesusongdiwei;
                    caseAngerid = anjianshiti.Anjianshitiid;
                    juese.Zhuzhangfangleixing = "";
                }
                else
                {
                    juese.Zhuzhangfangleixing = caseetiyinfoid;
                    juese.Zhuzhangfangjihe = caseAngerid;

                }

                // 对角色的当事人类型赋值
                if (datacontext.DataLayerAns.Anjianshitis == null)
                {
                    datacontext.DataLayerAns.Anjianshitis = new List<An_anjianshiti>();
                }
                if (anjianshiti.Anjianshitijueses == null)
                {
                    anjianshiti.Anjianshitijueses = new List<An_anjianshitijuese>();
                }
                anjianshiti.Anjianshitijueses.Add(juese);
                if (datacontext.DataLayerAns.Anjianshitijueses == null)
                {
                    datacontext.DataLayerAns.Anjianshitijueses = new List<An_anjianshitijuese>();
                }
                datacontext.DataLayerAns.Anjianshitijueses.Add(juese);
                if (datacontext.DataLayerAns.Anjianshitis?.FirstOrDefault(a => a.Mingcheng == anjianshiti.Mingcheng) == null)
                {
                    datacontext.DataLayerAns.Anjianshitis.Add(anjianshiti);
                }
                else
                {
                    var c = datacontext.DataLayerAns.Anjianshitis.FirstOrDefault(a => a.Mingcheng == anjianshiti.Mingcheng);
                    c = anjianshiti;
                }


            }
        }

        /// <summary>
        /// 计算人员角色下标
        /// </summary>
        /// <param name="SuitDegreeID"></param>
        /// <returns></returns>
        private int PersonnelReadIndex(string SuitDegreeID)
        {
            int ReadIndex = 0;
            if (datacontext.DataLayerAns.Anjianshitis != null)
            {
                //var caseEntityInfoList = dataContext.DataLayerAns.Anjianshitis[0].Anjianshitijueses.Where(a => a.Juesesusongdiwei == SuitDegreeID).ToList();

                var caseEntityInfoList = datacontext.DataLayerAns.Anjianshitis.Where(a => a.Anjianshitijueses.FirstOrDefault(b => b.Juesesusongdiwei == SuitDegreeID) != null).ToList();
                ReadIndex = caseEntityInfoList.Count + 1;
            }
            return ReadIndex;
        }
        /// <summary>
        /// 根据匹配内容获取参数值
        /// </summary>
        /// <param name="matchKeyWords">匹配内容</param>
        /// <param name="originalValue">原始值</param>
        /// <returns>参数值</returns>
        private string GetArgumentValueByMatchWords(string matchKeyWords, string originalValue)
        {
            string fieldValue = originalValue;
            matchKeyWords = Regex.Replace(matchKeyWords, @"(?<=;)\s", "", RegexOptions.Singleline);
            if (matchKeyWords != string.Empty)
            {
                fieldValue = (fieldValue == string.Empty) ? "空" : fieldValue;
                string paternStr = "(?<=^|；|;)[^=]+(?==(?:[^=；;]*[,，]*?)(?<![\u4E00-\u9FFF\r，、]){MatchKeyWord}[,;；])";
                string currPatern = paternStr.Replace("{MatchKeyWord}", fieldValue);
                string extractValue = Regex.Match(matchKeyWords.Replace("\r", ""), currPatern, RegexOptions.Singleline).Value.Trim(); //返回匹配到的编号值！
                if (extractValue == string.Empty && fieldValue != "空")
                {
                    //01.假如当前匹配值，满足1）未匹配成功。2）本身就是匹配字典值中的一个。则直接返回。
                    if (Regex.IsMatch(matchKeyWords, @"(?:^|;)" + originalValue + "="))
                    {
                        return originalValue;
                    }
                    //02.上述没匹配成功，则再进行其他匹配。
                    currPatern = paternStr.Replace("{MatchKeyWord}", "其他");
                    extractValue = Regex.Match(matchKeyWords, currPatern, RegexOptions.Singleline).Value;    //返回匹配到的编号值！
                    extractValue = extractValue.Replace("\r", "");//2017-09-12 ljx 添加提取出来的结果存在 ”\r\r\r内容“这样的类型值
                }
                if (extractValue == string.Empty)
                {
                    return "";
                }
                else
                {
                    return extractValue;
                }
            }
            return originalValue;
        }
        /// <summary>
        /// 根据配置获取表实体
        /// </summary>
        /// <param name="parentID">上级ID</param>
        /// <param name="dicFileClonment">主键ID</param>
        /// <param name="xmlNodeData">数据源</param>
        public void SetDicTabel(string parentID, Dictionary<string, string> dicFileClonment, XmlNode xmlNodeData, DataContext dynamicDataStores)
        {
            List<TableConverModel> tableConverList = ConverDataTabelModelConfig.tableConverModelList.Where(a => a.prentid == null).ToList();
            foreach (TableConverModel tableConverModel in tableConverList)
            {
                string tabelename = "";
                string priority = tableConverModel.priority;
                if (priority.ToLower() == "all")
                {
                    ReadDicTabel(tableConverModel, dynamicDataStores, xmlNodeData, dicFileClonment, tabelename, "");
                }
                else
                {
                    string[] priorit = tableConverModel.priority.Split('>');
                    foreach (string prioritid in priorit)
                    {
                        ReadDicTabel(tableConverModel, dynamicDataStores, xmlNodeData, dicFileClonment, tabelename, prioritid);
                        if (DicTable.ContainsKey(tabelename))
                        {
                            //已匹配成功跳出循环
                            break;
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 表数据添加
        /// </summary>
        /// <param name="tableConverModel">表配置实体</param>
        /// <param name="dynamicDataStores">中间数据层</param>
        /// <param name="xmlNodeData">数据节点</param>
        /// <param name="dicFileClonment">表主键集合</param>
        /// <param name="tabelename">表名</param>
        /// <param name="Prioritid">节点主键ID</param>
        public void ReadDicTabel(TableConverModel tableConverModel, DataContext dynamicDataStores, XmlNode xmlNodeData, Dictionary<string, string> dicFileClonment, string tabelename, string Prioritid)
        {
            List<Dictionary<string, string>> dicfieldList = new List<Dictionary<string, string>>();
            List<XmlPathModel> xmlPathList = new List<XmlPathModel>();
            if (string.IsNullOrEmpty(Prioritid))
            {
                xmlPathList = tableConverModel.XmlPathListModel.xmlPathList;
            }
            else
            {
                xmlPathList = tableConverModel.XmlPathListModel.xmlPathList.Where(a => a.code == Prioritid).ToList();
            }

            foreach (XmlPathModel pathmodel in xmlPathList)
            {
                XmlNodeList xmlNodeList = xmlNodeData.SelectNodes(pathmodel.value);

                if (pathmodel.value == "/")
                {
                    XmlNode xmlNodeField = xmlNodeData;

                    Dictionary<string, string> dicfield = new Dictionary<string, string>();

                    foreach (FileNameModel fileName in pathmodel.fileNameModelList)
                    {
                        string fileNameValue = fileName.value.Replace("@", "");
                        if (xmlNodeField.Attributes[fileNameValue] != null)
                        {
                            if (fileName.name.ToLower() == "caseid")
                            {

                                string caseid = dynamicDataStores.DataLayerAns.CaseId;

                                dicfield.Add(fileName.name.ToLower(), caseid);
                            }
                            else
                            {
                                dicfield.Add(fileName.name.ToLower(), xmlNodeField.Attributes[fileNameValue].Value);
                            }

                        }
                    }
                    foreach (ElmentConvertModel elementModel in pathmodel.elmentConvertModelList)
                    {
                        XmlNode xmlNodefield = xmlNodeData.SelectSingleNode(elementModel.xmlPath);
                        foreach (FileNameModel fileName in elementModel.fileNameModelList)
                        {
                            string fileNameValue = fileName.value.Replace("@", "");
                            if (xmlNodefield != null)
                            {
                                if (xmlNodefield.Attributes[fileNameValue] != null)
                                {
                                    try
                                    {
                                        dicfield.Add(fileName.name.ToLower(), xmlNodefield.Attributes[fileNameValue].Value);
                                    }
                                    catch (System.Exception)
                                    {
                                        dynamicDataStores.InteractiveShow.LogShow("对比出错，出现多个相同字段重复匹配！字段：" + fileName.name);

                                    }
                                }
                            }
                        }
                    }
                    if (dicFileClonment != null)
                    {
                        dicfield.Add(dicFileClonment.First().Key, dicFileClonment.First().Value);
                    }
                    dicfieldList.Add(dicfield);

                    if (DicTable.ContainsKey(tabelename))
                    {
                        DicTable[tabelename].Add(dicfield);
                    }
                    else
                    {
                        DicTable.Add(tabelename, dicfieldList);
                    }
                    dynamicDataStores.InteractiveShow.LogShow(tabelename + "表信息" + JsonConvert.SerializeObject(DicTable[tabelename]));
                    Dictionary<string, string> dicpk = new Dictionary<string, string>();
                    dicpk.Add(dicfield.FirstOrDefault().Key, dicfield.FirstOrDefault().Value);
                    SetDicTabel(tableConverModel.id, dicpk, xmlNodeField, dynamicDataStores);
                }
                else
                {
                    foreach (XmlNode xmlNodeField in xmlNodeList)
                    {
                        Dictionary<string, string> dicfield = new Dictionary<string, string>();

                        foreach (FileNameModel fileName in pathmodel.fileNameModelList)
                        {
                            string fileNameValue = fileName.value.Replace("@", "");
                            if (xmlNodeField.Attributes[fileNameValue] != null)
                            {
                                try
                                {
                                    if (fileName.name == "caseid")
                                    {

                                        string caseid = dynamicDataStores.DataLayerAns.CaseId;

                                        dicfield.Add(fileName.name.ToLower(), caseid);
                                    }
                                    else
                                    {
                                        dicfield.Add(fileName.name.ToLower(), xmlNodeField.Attributes[fileNameValue].Value);
                                    }
                                }
                                catch (System.Exception)
                                {

                                    string fff = "";
                                }


                            }
                            
                        }
                        dicfieldList.Add(dicfield);
                        foreach (ElmentConvertModel elementModel in pathmodel.elmentConvertModelList)
                        {//案件信息要素中心/执行实施/详情/立案阶段
                            XmlNode xmlNodefield = xmlNodeField.SelectSingleNode(elementModel.xmlPath);
                            if (elementModel.xmlPath == "/")
                            {
                                xmlNodefield = xmlNodeData;
                            }
                            dicfield = new Dictionary<string, string>();
                            foreach (FileNameModel fileName in elementModel.fileNameModelList)
                            {
                                string fileNameValue = fileName.value.Replace("@", "");
                                if (xmlNodefield != null)
                                {
                                    if (xmlNodefield.Attributes[fileNameValue] != null)
                                    {
                                        try
                                        {
                                            dicfield.Add(fileName.name.ToLower(), xmlNodefield.Attributes[fileNameValue].Value);
                                        }
                                        catch (System.Exception)
                                        {

                                            string ii = "";
                                        }

                                    }
                                }

                            }
                            if (dicfield!=null && dicfield.Count>0)
                            {
                                dicfieldList.Add(dicfield);
                            }
                           
                        }
                        foreach (ChildNodeConvertModel childNodeConvertModel in pathmodel.childNodeConvertModels)
                        {
                            XmlNode xmlNodefield = xmlNodeField.SelectSingleNode(childNodeConvertModel.xmlPath);

                            if (childNodeConvertModel.xmlPath == "/")
                            {
                                xmlNodefield = xmlNodeData;
                            }
                            foreach (FileNameModel fileName in childNodeConvertModel.fileNameModelList)
                            {
                                string fileNameValue = fileName.value.Replace("@", "");
                                if (xmlNodefield != null)
                                {
                                    if (xmlNodefield.Attributes[fileNameValue] != null)
                                    {
                                        try
                                        {
                                            dicfield.Add(fileName.name.ToLower(), xmlNodefield.Attributes[fileNameValue].Value);
                                        }
                                        catch (System.Exception)
                                        {

                                            string ii = "";
                                        }

                                    }
                                }

                            }
                        }
                        if (dicFileClonment != null)
                        {
                            dicfield.Add(dicFileClonment.First().Key, dicFileClonment.First().Value);
                        }
                        
                        if (DicTable.ContainsKey(tabelename))
                        {
                            DicTable[tabelename].Add(dicfield);
                        }
                        else
                        {
                            DicTable.Add(tabelename, dicfieldList);
                        }
                        Dictionary<string, string> dicpk = new Dictionary<string, string>();
                        if (dicfield!=null && dicfield.Count>0)
                        {
                            dicpk.Add(dicfield.FirstOrDefault().Key, dicfield.FirstOrDefault().Value);
                        }
                        
                        SetDicTabel(tableConverModel.id, dicpk, xmlNodeField, dynamicDataStores);
                    }
                }

            }
        }


    }
}
